const db = require('../db')

exports.ping = (req, res) => {
    let sqlStr = `SELECT * FROM pingluen`
    let index = 1
    let is = 1

    if (req.body.yl != undefined) { //发表言论
        let sqlStr1 = `insert into pingluen (`
        let sqlStr2 = `  values (`
        for (p in req.body) {
            sqlStr1 += `${p},`
            sqlStr2 += ` "${req.body[p]}",`
        }
        sqlStr1 += 'hot,username)'
        sqlStr2 += '0, "test" )'
        sqlStr = sqlStr1 + sqlStr2
        is = 2
    } else if (req.body.tui == 'tui') {
        sqlStr = ` SELECT * FROM pingluen where caricatureId = '${req.body.caricatureId}' LIMIT 0,5`//查询5个
    } else if (req.body.hot == 'up') {
        sqlStr = `update pingluen set hot=hot+1 where id = ${req.body.id} `//点赞
    } else if (req.body.hot == 'down') {
        sqlStr = `update pingluen set hot=hot-1 where id = ${req.body.id} `//取消点赞
    } else if (req.body.del == 'del') {
        sqlStr = `DELETE FROM pingluen WHERE id = ${req.body.id};`//取消评论
    } else {//查询特定
        for (p in req.body) {
            if (req.body[p] == 0) {
                continue
            } else if (index == 1) {
                sqlStr += ` where ${p}= '${req.body[p]}'`
                index++
            } else {
                sqlStr += ` and ${p}= '${req.body[p]}'`
            }
        }

    }
    if (req.body.sum != 'sum') {
        db.query(sqlStr, (err, results) => {
            if (err) return res.cc(err)
            if (results == 0) return res.cc('快来抢沙发!')
            if (is == 1) {
                return res.send(results)
            } else if (is == 2) {
                return res.cc('成功!', 0)
            }
        })
    } else {
        const sqlStr2 = `select  count(yl) from pingluen where caricatureId = ? `
        db.query(sqlStr2, req.body.caricatureId, (err, results) => {
            if (err) return res.cc(err)
            let sum = ''
            for (p in results[0]) {
                sum = results[0][p]
            }
            res.cc(sum, 0)
        })
    }
}

//添加图片
// exports.img = (req, res) => {
//     console.log(req);
//     fs.readFile(req.file.path, (err, data) => {
//         if (err) return res.cc('上传失败!')
//         //如果读取成功
//         //声明图片名字为时间戳和随机数拼接成的，尽量确保唯一性
//         let time = Date.now() + parseInt(Math.random() * 999) + parseInt(Math.random() * 2222);
//         //拓展名
//         let extname = req.file.mimetype.split('/')[1]
//         //拼接成图片名
//         let keepname = time + '.' + extname
//         fs.writeFile(path.join(__dirname, '../userimg/' + keepname), data, (err) => {
//             if (err) { return res.send('写入失败') }
//             res.send({ err: 0, msg: '上传ok', data: '/userimg/' + keepname })
//         })
//     })
// }